package com.czk.netty.zerocopy;

import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/12 22:21
 */
public class NewNioServer {
    public static void main(String[] args) throws Exception {
        // 端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7001);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 绑定端口
        serverSocketChannel.bind(inetSocketAddress);
        // 创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 监听
        FileOutputStream fileOutputStream=new FileOutputStream("d://1.txt");
        FileChannel channel = fileOutputStream.getChannel();
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            int readCount = 0;
            while (readCount != -1) {
                try {
                    readCount = socketChannel.read(byteBuffer);
                    byteBuffer.flip();
                    channel.write(byteBuffer);
                } catch (Exception ex) {

                }
                // 倒带 position=0
                byteBuffer.rewind();
                channel.close();
                fileOutputStream.close();
            }
        }
    }
}

